import org.grails.plugins.springsecurity.service.AuthenticateService

class SettingsController {

    AuthenticateService authenticateService
	def daoAuthenticationProvider

	def allowedMethods = [save: 'POST', update: 'POST']

	/**
	 * User Registration Top page
	 */
	def index = {

		if (authenticateService.userDomain() && session.id) {
            log.info("settings")
            render(view: 'index')
		}
        else {
            redirect(controller: 'login')
        }
	}

	/**
	 * User Information page for current user.
	 */
	def profile = {

		//get user id from session's domain class.
		def user = authenticateService.userDomain()
		if (user) {
			render(view: 'profile', model: [person: User.get(user.id)])
		}
		else {
			redirect(action: 'index')
		}
	}

	/**
	 * Edit page for current user.
	 */
	def edit = {

		def person
		def user = authenticateService.userDomain()
		if (user) {
			person = User.get(user.id)
		}

		if (!person) {
			flash.message = "[Illegal Access] User not found with id ${params.id}"
			redirect(action: 'index')
			return
		}

		[person: person]
	}

	/**
	 * update action for current user's edit page
	 */
	def update = {

		def person
		def user = authenticateService.userDomain()
		if (user) {
			person = User.get(user.id)
		}
		else {
			redirect(action: 'index')
			return
		}

		if (!person) {
			flash.message = "[Illegal Access] User not found with id ${params.id}"
			redirect(action: 'index', id: params.id)
			return
		}

		person.userRealName = params.userRealName
		person.email = params.email
		if (params.emailShow) {
			person.emailShow = true
		}
		else {
			person.emailShow = false
		}

		if (person.save()) {
			redirect(action: 'profile', id: person.id)
		}
		else {
			render(view: 'edit', model: [person: person])
		}
	 }

    def changePasswd = {
    }

    def savePasswd = {

        def person
		def user = authenticateService.userDomain()
		if (user) {
			person = User.get(user.id)
		}

		if (!person) {
			flash.message = "[Illegal Access] User not found with id ${params.id}"
			redirect(action: 'index')
			return
		}


        if (params.passwd && params.passwd.length() > 0
				&& params.repasswd && params.repasswd.length() > 0) {
			if (params.passwd == params.repasswd) {
				person.passwd = authenticateService.passwordEncoder(params.passwd)
                if (person.save()) {
                    flash.message = 'Password Changed.'
                    redirect(action: 'index')
                }
                else {
                    render(view: 'changePasswd')
                }
			}
			else {
				flash.message = 'The passwords you entered do not match.'
				render(view: 'changePasswd')
				return
			}
		}
    }
}
